package com.extract.task.basic;

import com.extract.query.DatabaseBuilder;
import com.extract.sys.entity.TaskRecord;
import com.extract.sys.service.ITaskRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-10-15 9:55
 */
@Slf4j
public abstract class AbstractTask implements ITask {

    @Autowired
    protected DatabaseBuilder databaseBuilder;

    @Autowired
    protected ITaskRecordService taskRecordService;

    /**
     * 任务执行处理方法
     *
     * @param taskRecord 任务记录
     */
    @Override
    public void execute(TaskRecord taskRecord) {
        if (Objects.isNull(taskRecord) || taskRecord.getIntervalNum() <= 0) {
            log.info("任务记录为空或处理数量为零：{}", taskRecord);
            return;
        }
        // 处理数量
        int handlerNum = 0;
        // 循环执行任务
        do {
            // 任务结果
            TaskResult taskResult = null;
            try {
                // 执行任务并返回结果
                taskResult = executeTask(taskRecord);
                handlerNum = taskResult.getHandlerNum();
            } catch (Exception ex) {
                log.error("执行任务异常: {}", taskRecord);
                log.error("执行任务异常", ex);
            }
            // 更新任务记录
            LocalDateTime now = LocalDateTime.now();
            taskRecord.setUpdateTime(now);
            if (Objects.nonNull(taskResult) && taskResult.isSuccess()) {
                taskRecord.setLastSign(taskResult.getLastSign());
                taskRecord.setLastSuccessTime(now);
            } else {
                taskRecord.setLastFailureTime(now);
            }
            taskRecordService.updateById(taskRecord);
        }while (handlerNum >= taskRecord.getIntervalNum());
    }

    /**
     * 执行任务抽象方法
     *
     * @param taskRecord 任务记录
     */
    public abstract TaskResult executeTask(TaskRecord taskRecord);
}
